import { createAVPlayer, AVPlayer, AVPlayerState } from '@ohos.multimedia.media';
import { KugouApi } from './KugouApi';
import { Song, PlayState } from './DataModel';
import common from '@ohos.app.ability.common';

/**
 * 音频播放控制器
 * 负责音乐播放、暂停、切换等操作
 */
export class AudioController {
  private static instance: AudioController;
  private player: AVPlayer | null = null;
  private api: KugouApi = new KugouApi();
  private context: common.UIAbilityContext | null = null;
  public playState: PlayState = {
    currentIndex: 0,
    songList: [],
    isPlaying: false,
    currentTime: 0,
    duration: 0
  };

  // 单例模式
  public static getInstance(context?: common.UIAbilityContext): AudioController {
    if (!this.instance) {
      this.instance = new AudioController(context);
    }
    return this.instance;
  }

  private constructor(context?: common.UIAbilityContext) {
    this.context = context;
    this.initPlayer();
  }

  // 初始化播放器
  private async initPlayer() {
    if (!this.player) {
      try {
        this.player = await createAVPlayer();

        // 监听播放器状态变化
        this.player.on('stateChange', (state: AVPlayerState) => {
          console.info(`Player state changed to: ${state}`);
          if (state === AVPlayerState.END_OF_STREAM) {
            this.playState.isPlaying = false;
            this.next(); // 自动播放下一首
          } else if (state === AVPlayerState.PLAYING) {
            this.playState.isPlaying = true;
          } else if (state === AVPlayerState.PAUSED) {
            this.playState.isPlaying = false;
          }
        });

        // 监听播放进度
        this.player.on('timeUpdate', (time: number) => {
          this.playState.currentTime = time / 1000; // 转换为秒
        });

        // 监听元数据变化
        this.player.on('metaDataChange', (metaData: any) => {
          if (metaData.duration) {
            this.playState.duration = metaData.duration / 1000; // 转换为秒
          }
        });

      } catch (error) {
        console.error('Failed to initialize player:', error);
      }
    }
  }

  // 播放歌曲
  async play(song: Song, songList: Song[] = [], index: number = 0) {
    await this.initPlayer();

    if (!this.player) {
      console.error('Player is not initialized');
      return;
    }

    try {
      // 如果提供了新的歌曲列表，则更新当前播放列表
      if (songList.length > 0) {
        this.playState.songList = songList;
        this.playState.currentIndex = index;
      }

      // 获取播放URL
      if (!song.playUrl) {
        song.playUrl = await this.api.getPlayUrl(song.hash, song.albumId);
      }

      // 重置播放器
      if (this.player.state !== AVPlayerState.IDLE) {
        await this.player.reset();
      }

      // 设置播放源
      await this.player.setSource({ url: song.playUrl });

      // 准备并播放
      await this.player.prepare();
      await this.player.play();

      this.playState.isPlaying = true;

    } catch (error) {
      console.error('Failed to play song:', error);
    }
  }

  // 播放当前播放列表中的指定索引歌曲
  async playIndex(index: number) {
    if (index >= 0 && index < this.playState.songList.length) {
      this.playState.currentIndex = index;
      await this.play(this.playState.songList[index]);
    }
  }

  // 暂停播放
  async pause() {
    if (this.player && this.playState.isPlaying) {
      try {
        await this.player.pause();
        this.playState.isPlaying = false;
      } catch (error) {
        console.error('Failed to pause player:', error);
      }
    }
  }

  // 继续播放
  async resume() {
    if (this.player && !this.playState.isPlaying) {
      try {
        await this.player.play();
        this.playState.isPlaying = true;
      } catch (error) {
        console.error('Failed to resume player:', error);
      }
    }
  }

  // 下一首
  async next() {
    if (this.playState.songList.length > 0) {
      this.playState.currentIndex = (this.playState.currentIndex + 1) % this.playState.songList.length;
      await this.play(this.playState.songList[this.playState.currentIndex]);
    }
  }

  // 上一首
  async prev() {
    if (this.playState.songList.length > 0) {
      this.playState.currentIndex = (this.playState.currentIndex - 1 + this.playState.songList.length) % this.playState.songList.length;
      await this.play(this.playState.songList[this.playState.currentIndex]);
    }
  }

  // 跳转到指定时间
  async seek(time: number) {
    if (this.player && time >= 0 && time <= this.playState.duration) {
      try {
        await this.player.seek(time * 1000); // 转换为毫秒
      } catch (error) {
        console.error('Failed to seek player:', error);
      }
    }
  }

  // 释放资源
  async release() {
    if (this.player) {
      try {
        await this.player.release();
        this.player = null;
      } catch (error) {
        console.error('Failed to release player:', error);
      }
    }
  }
}